<?php
namespace app\admin\controller;
use think\Db;
use think\Paginator;

class Shop extends Base
{
    public function index(){
        if(request()->isAjax ()){
            extract (input ());
            $map = [];
            if(isset($key)&&$key!="")
            {
                $map['shop_contact|shop_account|shop_phone|shop_name'] = ['like',"%" . $key . "%"];
            }
            if(isset($faceSerialNo) && $faceSerialNo == "1")
            {
                $map['shop_face_serial_no'] = ['NEQ','NULL'];
            }
            if(session ('area')){
                $map['shop_qu_id'] = ['in',session('area')];
            }
            $map['shop_attestation'] = 2;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('shop s')
                ->join('u_user u','u.user_id = s.shop_user_id','left')
                ->join('admin a','a.id = s.shop_superior_agent','left')
                ->join('area p','p.district_id = s.shop_sheng_id','left')
                ->join('area c','c.district_id = s.shop_city_id','left')
                ->join('area q','q.district_id = s.shop_qu_id','left')
                ->where($map)
                ->count();
            $lists = Db::name('shop s')
                ->join('u_user u','u.user_id = s.shop_user_id','left')
                ->join('admin a','a.id = s.shop_superior_agent','left')
                ->join('area p','p.district_id = s.shop_sheng_id','left')
                ->join('area c','c.district_id = s.shop_city_id','left')
                ->join('area q','q.district_id = s.shop_qu_id','left')
                ->join('shop_copy sc','s.shop_id = sc.sc_shop_id','left')
                ->where($map)
                ->field('s.*,u.user_id,u.user_username,a.username,p.district sheng,c.district shi,q.district qu,sc_mch_id')
                ->page($Nowpage,$limits)
                ->order('shop_time DESC')
                ->select ();
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        return $this->fetch ('shop/index');
    }


    public function check(){
        if(request()->isAjax ()){
            extract (input ());
            $map = [];
            if(isset($key)&&$key!="")
            {
                $map['user_username|shop_name'] = ['like',"%" . $key . "%"];
            }
            if(session ('area')){
                $map['shop_qu_id'] = ['in',session('area')];
            }
            $map['shop_attestation'] = 3;
            $map['dx_status'] = 2;
            $map['dx_qian_status'] = 2;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('shop s')
                ->join('u_user u','u.user_id = s.shop_user_id','left')
                ->join('admin a','a.id = s.shop_superior_agent','left')
                ->join('area p','p.district_id = s.shop_sheng_id','left')
                ->join('area c','c.district_id = s.shop_city_id','left')
                ->join('area q','q.district_id = s.shop_qu_id','left')
                ->where($map)
                ->count();
            $lists = Db::name('shop s')
                ->join('u_user u','u.user_id = s.shop_user_id','left')
                ->join('admin a','a.id = s.shop_superior_agent','left')
                ->join('area p','p.district_id = s.shop_sheng_id','left')
                ->join('area c','c.district_id = s.shop_city_id','left')
                ->join('area q','q.district_id = s.shop_qu_id','left')
                ->where($map)
                ->field('s.*,u.user_id,u.user_username,a.username,p.district sheng,c.district shi,q.district qu,shop_hand_img,shop_ldentity_img,shop_facade_img')
                ->page($Nowpage,$limits)
                ->order('shop_time')
                ->select ();
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        return $this->fetch ('shop/check');
    }

    public function write_admin_log($data)
    {
        file_put_contents ( APP_PATH."api/controller/checkShop_user_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $data . "\r\n", FILE_APPEND );
    }


    public function doCheck(){
        extract (input());
        $user = Db::name('u_user')->where('user_id',$user_id)->find();
        $ago = Db::name('shop')->where(['shop_attestation'=>2,'shop_account'=>$user['user_phone']])->find();
        if(!empty($ago)){
            return json(['code'=>100,'msg'=>'请勿重复审核']);
        }
        if (empty($temp) || $temp != 101) {
            return json(['code'=>100,'msg'=>'审核错误，请通过正确的方式审核']);
        }
        $this->write_admin_log("response: ".$shop_id.var_export($user,true));
        Db::startTrans ();
        try{
            $shop = Db::name('shop')->where('shop_id',$shop_id)->find();
            $param = [
                'n_to'=>1,
                'n_title'=>'店铺审核',
                'n_type'=>1,
                'n_user_id'=>$user_id,
                'n_read'=>',0,',
                'n_delete'=>',0,',
                'n_time'=>date('Y-m-d H:i:s')
            ];
            if($type == 2){	//通过
				$msg = trim($msg,' ');
				if(md5(md5($msg)) == 'dc78f8c258966a8ae10ba0e62bc821e4'){
//                    $shouMa = new \app\api\controller\Shop();
//                    $skmRes = $shouMa->getQRCodeForAdmin($shop_id);
//                    if($skmRes['code'] == 200) return json($skmRes);
                    Db::name('shop')->where('shop_id',$shop_id)->update ([
                        'shop_attestation' => $type,
                        'shop_ratio' => $shop_ratio,
//                        'shop_qr_code' => $skmRes['msg'],
                        'shop_admin_id' => session ('uid'),
                        'shop_authentication_time' => date('Y-m-d H:i:s')
                    ]);
                    $param['n_content'] = '店铺审核通过，默认登陆密码为'.$shop['shop_rand'].'，请尽快登陆支分宝商户版APP修改密码。';
					Db::name('u_user')->where('user_id',$user_id)->update (['user_level2'=>2,'user_one_pay'=>3,'user_edit_time'=>date('Y-m-d H:i:s')]);
					https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode(['username'=>'jifenshop'.$shop_id,'password'=>'123456789','nickname'=>'']),'POST');
				}else{
					return json(['code'=>100,'msg'=>'输入有误！']);
				}
            }else{//驳回
                $param['n_content'] = '店铺审未通过：'.$msg;
                Db::name('u_user')->where('user_id',$user_id)->update (['user_one_pay'=>5,'user_edit_time'=>date('Y-m-d H:i:s')]);//已填写资料
            }
            try{
                $this->jpushUser(1,$user_id,$param['n_content'],json([]));
            }catch (\Exception $e){

            }
            Db::name('notice')->insert ($param);
            Db::commit ();
            return json(['code'=>200,'msg'=>'审核成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['code'=>100,'msg'=>'审核失败']);
        }
    }

    public function addSon(){
        extract (input());
        if(request()->isPost ()){
            $have = Db::name('shop')->where('shop_account',$value)->find();
            if(!empty($have)){
                return json(['code'=>100,'msg'=>'该手机号已是店主']);
            }
            $res = Db::name('shop')->where('shop_id',$shop_id)->update (['shop_son'=>$value,'shop_son_password'=>$password]);
            if($res){
                return json(['code'=>200,'msg'=>'添加成功']);
            }else{
                return json(['code'=>100,'msg'=>'添加失败']);
            }
        }else{
            return $this->fetch ('add_son',['id'=>$id]);
        }

    }


    public function shopStatus(){
        extract (input());
        if($num == 2){
            $msg = '禁用';
        }else{
            $msg = '启用';
        }
        $res = Db::name('shop')->where(['shop_id'=>$id])->setField ('shop_status',$num);
        if(!$res){
            return json(['code'=>100,'msg'=> $msg.'失败']);
        }
    }

    public function shopStatus1(){
        extract (input());
        if($num == 2){
            $msg = '取消';
        }else{
            $msg = '加入';
        }
        $res = Db::name('shop')->where(['shop_id'=>$id])->setField ('shop_native',$num);
        if(!$res){
            return json(['code'=>100,'msg'=> $msg.'失败']);
        }
    }


    public function sonDel(){
        extract (input());
        $res = Db::name('shop')->where('shop_id',$id)->update (['shop_son'=>'','shop_son_password'=>'']);
        if($res){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }


    public function recordList(){
        extract (input());
        if(request()->isAjax ()){
            $map = [];
            if(isset($key)&&$key!="")
            {
                $map['record_number'] = ['like',"%" . $key . "%"];
            }
			if(isset($type)&&$type!="")
            {
                $map['record_type'] = $type;
            }
            $map['record_shop_id'] = session('record_shop_id');
            $map['record_status'] = 2;
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::name('record')
                ->where($map)
                ->count();
            $lists = Db::name('record r')
                ->join("u_user u",'r.record_user_id = u.user_id','left')
                ->join("shop s",'r.record_shop_id = s.shop_id','left')
                ->where($map)
                ->page($Nowpage,$limits)
                ->order('record_pay_time DESC')
                ->select ();
            $map['record_shop_id'] = session('record_shop_id');
            $map['record_status'] = 2;
            $map['record_fws'] = 1;
            $getget = Db::name('record')
                ->where($map)
                ->sum('record_money');
            $getget2 = Db::name('order')
                ->where('o_shop_id',session('record_shop_id'))
                ->where('o_type',1)
                ->where('o_status','in','2,3,4,5')
                ->sum('o_jifen');
            $getget3 = Db::name('order')
                ->where('o_shop_id',session('record_shop_id'))
                ->where('o_type',2)
                ->where('o_status','in','2,3,4,5')
                ->sum('o_money');
            $outout = Db::name('order')
                ->where('o_shop_id',session('record_shop_id'))
                ->where('o_type',3)
                ->where('o_tixian_status',2)
                ->sum('o_money');
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists,'getget'=>$getget,'getget2'=>$getget2*0.2+$getget3,'outout'=>$outout]);
        }
        session('record_shop_id',$id);
        return $this->fetch ('shop/record_list');
    }

    public function ratio(){
        extract (input());
        if (Request()->isAjax()) {
            $shop_id = input('shop_id');
            $value = input('value');
            $res = Db::name('shop')->where('shop_id',$shop_id)->update (['shop_ratio'=>$value]);
            if($res){
                return json(['code'=>200,'msg'=>'添加成功']);
            }else{
                return json(['code'=>100,'msg'=>'添加失败']);
            }
        }
        $shop = DB::name('shop')->where('shop_id',$id)->find();
        $this->assign('shop',$shop);
        return view();
    }

    /**
     * 设置商户号
     * @return mixed
     */
    public function setMch(){
        if(Request()->isPost()){
            extract(input());
            $mch_id = trim($mch_id,' ');
            if(!$mch_id) return json(['code' => 100, 'msg' => '商户号不能为空！']);
            $have = Db::table('up_shop_copy')
                ->where('sc_shop_id',$shop_id)
                ->find();
            if($have){
                $can = Db::table('up_shop_copy')
                    ->where('sc_id','<>',$have['sc_id'])
                    ->where('sc_mch_id',$mch_id)
                    ->find();
                if($can) return json(['code' => 100, 'msg' => '已经有此商户号了！']);
                $data = [
                    'sc_mch_id' => $mch_id,
                    'sc_status' => 3,
                    'sc_time' => date('Y-m-d H:i:s')
                ];
                $res = Db::table('up_shop_copy')
                    ->where('sc_shop_id',$shop_id)
                    ->update($data);
            }else{
                $can = Db::table('up_shop_copy')
                    ->where('sc_mch_id',$mch_id)
                    ->find();
                if($can) return json(['code' => 100, 'msg' => '已经有此商户号了！']);
                $data = [
                    'sc_shop_id' => $shop_id,
                    'sc_mch_id' => $mch_id,
                    'sc_status' => 3,
                    'sc_time' => date('Y-m-d H:i:s')
                ];
                $res = Db::table('up_shop_copy')->insert($data);
            }
            if($res){
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $shop_id = input('shop_id');
        $mch_id = input('mch_id');
        if(!$mch_id || $mch_id == null || $mch_id == 'null' || $mch_id == 'null ') $mch_id = '';
        $this->assign('shop_id',$shop_id);
        $this->assign('mch_id',$mch_id);
        return $this->fetch('shop/setmch');
    }
    /**
     * 审核同意或拒绝
     * @return mixed
     */
    public function checkcheck(){
        $shop_id = input('shop_id');
        $user_id = input('user_id');
        $have = Db::table('up_shop')
            ->where('shop_id',$shop_id)
            ->value('shop_ratio');
        $this->assign('shop_id',$shop_id);
        $this->assign('user_id',$user_id);
        $this->assign('have',$have);
        return $this->fetch('shop/checkcheck');
    }

}